//
//  ZODInternalTools.m
//  ZTEOnlineDoc
//
//  Created by 万伟琦 on 2018/9/10.
//  Copyright © 2018年 万伟琦. All rights reserved.
//

#import "ZODInternalTools.h"
#import <objc/runtime.h>

#import "ZODFileInfo.h"
#import "ZODViewInfo.h"
#import "ZODAttInfo.h"
#import "ZODGlobalStorage.h"

@implementation ZODInternalTools

+ (NSDictionary *)dictionaryFromJSONString:(NSString *)str {
    if (str == nil) {
        return nil;
    }
    
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (NSData *)JSONDataFromDictionary:(NSDictionary *)dict {
    NSError *err;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&err];
    if (!err) {
        return jsonData;
    }else {
        return nil;
    }
}

+ (NSString *)JSONStringFromDictionary:(NSDictionary *)dict {
    NSString *jsonStr;
    NSData *jsonData = [self JSONDataFromDictionary:dict];
    if (jsonData) {
        jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonStr;
}

+ (NSString *)JSONStringFromObject:(id)obj {
    NSDictionary *dict = [self dictionaryFromObject:obj];
    NSString *jsonStr = [self JSONStringFromDictionary:dict];
    return jsonStr;
}



+ (ZODFileInfo *)getFileInfoFromAttInfo:(ZODAttInfo *)attInfo {
    ZODFileInfo *fileInfo = [[ZODFileInfo alloc] init];
    fileInfo.md5 = (!attInfo.RID || attInfo.RID.length < 1 )? attInfo.ID : attInfo.RID; //有 RID 优先使用 RID
    fileInfo.fileName = attInfo.N;
    
    NSString *baseURL = [ZODGlobalStorage sharedStorage].preConvertBaseURLString;
    NSDictionary *dict = [ZODInternalTools dictionaryFromObject:attInfo];
    fileInfo.fileUrl = [self composeGETURLWithBaseURL:baseURL parameters:dict].path;
    fileInfo.page = @"5";
    
    return fileInfo;
}

+ (ZODViewInfo *)getViewInfoFromAttInfo:(ZODAttInfo *)attInfo {
    ZODViewInfo *viewInfo = [[ZODViewInfo alloc] init];
    viewInfo.md5 = (!attInfo.RID || attInfo.RID.length < 1 )? attInfo.ID : attInfo.RID; //有 RID 优先使用 RID
    viewInfo.fileName = attInfo.N;
    viewInfo.uid = [ZODGlobalStorage sharedStorage].configuration.userNo;
    
    NSString *baseURL = [ZODGlobalStorage sharedStorage].previewBaseURLString;
    NSDictionary *dict = [ZODInternalTools dictionaryFromObject:attInfo];
    viewInfo.fileUrl = [self composeGETURLWithBaseURL:baseURL parameters:dict].absoluteString;
    
    return viewInfo;
}


+ (NSURL *)composeGETURLWithBaseURL:(NSString *)urlStr parameters:(NSDictionary *)paras {
    // 参数拼接。 遍历参数字典, 逐个取出参数, 按照参数格式拼接在 url 后面.
    NSMutableString *strM = [[NSMutableString alloc] init];
    
    [paras enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSString* obj, BOOL * _Nonnull stop) {
        [strM appendFormat:@"%@=%@&",key,[obj stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }];
    NSString *urlString = [NSString stringWithFormat:@"%@?%@",urlStr,strM];
    // 去掉最后多出的一个 '&' 字符
    urlString = [urlString substringToIndex:urlString.length - 1];
    NSURL *url = [NSURL URLWithString:urlString];
    NSLog(@"urlString:%@",urlString);
    
    return url;
}

#pragma mark - Internal

+ (NSDictionary*)dictionaryFromObject:(id)obj

{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    unsigned int propsCount;
    
    objc_property_t *props = class_copyPropertyList([obj class], &propsCount);//获得属性列表
    
    for(int i = 0;i < propsCount; i++)
        
    {
        
        objc_property_t prop = props[i];
        
        
        NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];//获得属性的名称
        
        id value = [obj valueForKey:propName];//kvc读值
        
        if(value == nil)
            
        {
            
            value = @"";
            
        }
        
        else
            
        {
            
            value = [self getObjectInternal:value];//自定义处理数组，字典，其他类
            
        }
        
        [dic setObject:value forKey:propName];
        
    }
    
    return dic;
    
}





+ (id)getObjectInternal:(id)obj

{
    
    if([obj isKindOfClass:[NSString class]]
       
       || [obj isKindOfClass:[NSNumber class]]
       
       || [obj isKindOfClass:[NSNull class]])
        
    {
        
        return obj;
        
    }
    
    
    
    if([obj isKindOfClass:[NSArray class]])
        
    {
        
        NSArray *objarr = obj;
        
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
        
        for(int i = 0;i < objarr.count; i++)
            
        {
            
            [arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];
            
        }
        
        return arr;
        
    }
    
    
    
    if([obj isKindOfClass:[NSDictionary class]])
        
    {
        
        NSDictionary *objdic = obj;
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
        
        for(NSString *key in objdic.allKeys)
            
        {
            
            [dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];
            
        }
        
        return dic;
        
    }
    
    return [self dictionaryFromObject:obj];
    
}

@end
